package com.eliza.springboot.v3.http.config

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import net.minidev.json.JSONUtil
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer
import org.springframework.security.core.Authentication
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.AuthenticationSuccessHandler


@EnableWebSecurity
@Configuration
class BasicSecurityConfig {
    @Bean
    @Throws(Exception::class)
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
//      拦截过滤
        http.authorizeHttpRequests() { registry ->
            registry.requestMatchers("*").permitAll()
//                其他都需要认证
                .anyRequest().authenticated()
        }
//         表单登录
        http.formLogin() { registry ->

            registry.successForwardUrl("http://192.168.20.5:8080/resp/map")

        }
//        http.csrf(Customizer.withDefaults())

        return http.build()
    }

    // 自定用户信息  自动依赖注入
    @Bean
    fun userData(passwordEncoder: PasswordEncoder): UserDetailsService {
        val withUsername = User
            .withUsername("as")
            .password(passwordEncoder.encode("as"))
            .roles("hr", "common")
            .authorities("w", "r")
            .build()
        val inMemoryUserDetailsManager = InMemoryUserDetailsManager()
        inMemoryUserDetailsManager.createUser(withUsername)
        return inMemoryUserDetailsManager
    }

    //     提供密码加密
    @Bean
    fun passwordEncoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }
}